﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace Demo3.Filters
{
    public class CustomActionFilterAttribute : Attribute, IAsyncActionFilter
    {
        private readonly ILogger<CustomActionFilterAttribute> _logger;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public CustomActionFilterAttribute(ILogger<CustomActionFilterAttribute> logger, IHttpContextAccessor httpContextAccessor)
        {
            _logger = logger;
            _httpContextAccessor = httpContextAccessor;

        }
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 计算接口响应时间
            var startTime = DateTime.Now;

            var request = context.HttpContext.Request;
            var url = request.Path;
            var method = request.Method;
            var areaName = context.ActionDescriptor.RouteValues["area"];
            var controllerName = context.ActionDescriptor.RouteValues["controller"];
            var actionName = context.ActionDescriptor.RouteValues["action"];
            var headers = JsonConvert.SerializeObject(request.Headers);

            var queryString = context.HttpContext.Request.QueryString.Value; // queryString

            // var requestBody = await context.HttpContext.Request.BodyReader.ReadAsync(); // 不成功



            ActionExecutedContext excutedContext = await next.Invoke(); // 执行Action方法

            var responseStatusCode = _httpContextAccessor.HttpContext.Response.StatusCode;
            var result = excutedContext.Result as ObjectResult;
            var responseBody = JsonConvert.SerializeObject(result.Value);
            var elapsedTime = (DateTime.Now - startTime).TotalMilliseconds; // 接口时间

            var logInfo = $"Reuest URL: {url} \n" +
                $"Request Method: {method} \n" +
                $"Request areaName:  {areaName} \n" +
                $"Request controllerName: {controllerName} \n" +
                $"Request actionName: {actionName} \n" +
                $"Request Headers: {headers} \n" +
                $"Request Query: {queryString} \n" +
                //  $"Request Body: {requestBody} \n" +
                $"Reponse Status Code: {responseStatusCode} \n" +
                $"Reponse Body: {responseBody} \n" +
                $"Elapsed Time: {elapsedTime} ms";

            Console.WriteLine(logInfo);
            _logger.LogInformation(logInfo);
        }

    }
}
